package com.lcc.service.Impl;

import com.lcc.pojo.Book;
import com.lcc.service.ImgUpService;
import org.apache.commons.fileupload.FileItem;
import org.springframework.stereotype.Service;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.UUID;

/**
 * /**
 *
 * @author 廖聪聪
 * @version 1.0
 * 创建时间 2020/7/23 17:53
 */
@Service
public class ImgUpServiceImpl implements ImgUpService {
	public Book upload(List<FileItem> fs) {
		String img_path = "";
		String public_dept = "";
		String book_price = "";
		String public_date = "";
		String book_auth = "";
		String summary = "";
		String book_name = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (FileItem f:fs){
        	try {
        		if (f.isFormField()){
        			String inputName = f.getFieldName();//取出表单元素的name属性值
					if ("public_dept".equals(inputName)){
						public_dept = f.getString("utf-8");
					}
					if ("book_price".equals(inputName)){
						book_price = f.getString("utf-8");
					}
					if ("public_date".equals(inputName)){
						public_date = f.getString("utf-8");
					}
					if ("book_auth".equals(inputName)){
						book_auth = f.getString("utf-8");
					}
					if ("summary".equals(inputName)){
						summary = f.getString("utf-8");
					}
					if ("book_name".equals(inputName)){
						book_name = f.getString("utf-8");
					}

				}else {
        			//说明是上传文件
					String oldName = f.getName();
					//UUID:随机生成一个32位了不重复的字符串sdsagvsagdyusagdyusad.jpg
					String newName = UUID.randomUUID() + oldName.substring(oldName.lastIndexOf("."));
					File newFile = new File("E:/tomcat8.0/webapps/img/" + newName);
					//把FileItem里面的二进制数据写到新文件中
					try {
						f.write(newFile);
					} catch (Exception e) {
						e.printStackTrace();
					}
					img_path = "http://localhost:8080/img/" + newName;
				}

			}catch (Exception e){
        		e.printStackTrace();
			}
		}
        Book book = new Book();
        book.setBook_auth(book_auth);
        book.setBook_name(book_name);
        if (book_price!=null&&!"".equals(book_price)){
        	book.setBook_price(new Double(book_price));
		}
        if (img_path!=null&&!"".equals(img_path)){
        	book.setImg_path(img_path);
		}
        if (public_date!=null&&!"".equals(public_date)){
			try {
				book.setPublic_date(sdf.parse(public_date));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
        book.setSummary(summary);
        book.setPublic_dept(public_dept);
		return book;
	}
}
